/**
 * 
 */
package com.zed.code.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @Copyright:copy from
 * @Project: epower
 * @FileName: EncodeUtil.java
 * @Description:进行AES加密
 * @Date:2017年9月30日
 * @Author:樊兆龙
 */
@SuppressWarnings("restriction")
public class EncodeUtil {

    public static String encrypt(String sSrc, String sKey, String datasecretiv) {
        try {
            if (sKey == null) {
                return "Key为空null";
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                return "Key长度不是16位";
            }
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec(datasecretiv.getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度1234567890123456 
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
            String str = new BASE64Encoder().encode(encrypted);
            str = str.replaceAll("\r", "");
            str = str.replaceAll("\n", "");
            return str;//new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (Exception ex) {
            //记日志
            return null;
        }
    }

    // 解密
    public static String decrypt(String sSrc, String sKey, String datasecretiv) {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                return "Key为空null";
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                return "Key长度不是16位";
            }
            byte[] raw = sKey.getBytes("UTF-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(datasecretiv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "UTF-8");
                return originalString;
            } catch (Exception e) {
                //日志
                return null;
            }
        } catch (Exception ex) {
            //日志
            return null;
        }
    }

}
